package tech.wetech.admin3.controller;

import com.alibaba.fastjson.JSONObject;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.AooUser;
import tech.wetech.admin3.sys.service.AooUserService;
import tech.wetech.admin3.sys.service.WxAuthService;
import tech.wetech.admin3.util.AooJwtUtil;
import tech.wetech.admin3.util.CustomResponse;


@RestController
@RequestMapping("/wx_auth")
@Slf4j
public class WxMiniAuthController {
  @Autowired
  private WxAuthService wxAuthService;
  @Autowired
  private AooUserService userService;
  @Autowired
  private AooJwtUtil jwtUtil;

  @PostMapping("/login")
  public ResponseEntity<?> login(@RequestBody WxLoginRequest obj) {
    try {
      return ResponseEntity.ok(new CustomResponse.r1("登录成功", true, wxAuthService.login(obj.code)));
    } catch (Exception e) {
      // 如果unionid为空，说明登录失败
      log.error("登录失败: {}", e.getMessage());
      return ResponseEntity.ok(new CustomResponse.r1("登录失败", false, e.getMessage()));
    }
  }

  @PostMapping("/getphonenumber")
  public JSONObject getPhoneNumber(@RequestBody WxGetPhoneNumberRequest obj, @RequestHeader("Authorization") String authorization) {
    log.info("authorization: {}", authorization);
    if (authorization == null || authorization.isEmpty()) {
      return null;
    }
    String token = authorization.substring(7);
    String unionid = jwtUtil.parseToken(token).getBody().getSubject();
    AooUser user = userService.findByEmail(unionid);
    log.info("user: {} \n", user);
    String sessionKey = user.getSessionKey();

    return wxAuthService.getPhoneNumber(sessionKey, obj.encryptedData, obj.iv);
  }

  record WxGetPhoneNumberRequest(@NotNull String encryptedData, @NotNull String iv) {
  }

  record WxLoginRequest(@NotNull String code) {
  }
}
